<template>
	<view class="grace-padding index_class">
		<div class="liveHeader">
			<div class="panel1">
				<h4 class="title">
					<p class="tipInfo">{{$t('共')}}{{userCartNum}} {{$t('件宝贝')}}</p>
				</h4>
				<div class="iconWrap" @click="manage">
					<text>{{magenaText}}</text>
				</div>
			</div>
		</div>
		<view class="cartWrap">
			<view class="cartCard" v-for="(itemList, keys) in cartlist" :key="keys">
				<!-- 分类 -->
				<view class="cart_top u-flex u-row-between u-p-25">
					<view class="cart_title">
						<i class="iconfont " style="padding-left:0;" :class="itemList.icon ? 'icon_e632' :'icon_e741'"
							@click="getShop(keys)"></i>

						<text
							@click.stop="getnav('/pagesC/shop/storeDetails?shop_id='+itemList.goodres[0].shop_id )">{{itemList.goodres[0].shop_name}}</text>
						<i class="iconfont icon_e60c"></i>
					</view>
					<text @click="copyjuan(itemList.goodres[0].shop_id)"
						v-if="itemList.couponinfos.is_show === 1">{{$t('领劵')}}</text>
				</view>

				<t-slide-vue ref="slide" :items="itemList.goodres" @del="del" @itemClick="goPage" class="grace-shoppingcard">
					<template v-slot:default="{item,index}">
						<view class="grace-shoppingcard">
							<view class="goods u-flex">
								<span class="noSelect" v-if="item.icon"></span>

								<i class="iconfont " style="padding-left:0;"
									:class="item.icon ? 'icon_e632' :'icon_e741'"
									@click.stop="isSelection(item.id,item.shop_id)"></i>
								<u-image :src="item.thumb_url " class="goodsCover" width="180" height="180"
									border-radius="12">
								</u-image>
								<view class="desc">
									<view class="goods-title grace-columns">
										<text class="to_name">{{item.goods_name}}</text>
										<text class="to_text">{{item.goods_attr_str}}</text>
									</view>
									<view class="goods-title grace-columns" v-if="item.is_activity !== 0">
										<view class="to_text">活动还剩{{item.sytime}}，
											<text class="to_text" v-if="item.is_activity == 1">
												限购{{item.xznum}}件
											</text>
										</view>
									</view>
									<view class="goods-price">
										<text class="color">￥{{item.shop_price}}</text>
										<view class="goods-number">
											<uni-number-box :index="index" :value="item.num" :idcode='item.id' :min="1"
												v-on:change="numberChange"
												:max="item.is_activity == 1 ? item.xznum : 10000">
											</uni-number-box>
										</view>
									</view>
								</view>
							</view>
						</view>
					</template>

				</t-slide-vue>

				<view class="grace_discount">
					<view v-if="itemList.couponinfos.is_show == 1">
						<text>{{itemList.couponinfos.infos}}</text>
					</view>
					<view class="grace-disp" v-if="itemList.promotions.is_show == 1">
						<view class="infos_list">
							<text v-for="(time,is_key) in itemList.promotions.infos" :key="is_key">{{time}}</text>
						</view>
					</view>
				</view>

			</view>

			<view class="depot" v-if="cartlist.length == 0 && !isLoading">


				<u-empty v-if="cartlist.length===0" :src="imgStaticUrl +'images/nullStatus/noCart.png'" icon-size="300"
					style="margin:0 auto" :text="$t('您的购物车空空如也')"></u-empty>
				<view class="stroll" @click="getnav('/pagesC/shop/shopList')">{{$t('到处逛逛')}}</view>
			</view>
			<loadMore :loadingType="loadingType"></loadMore>
		</view>
		<!-- 底部  -->
		<view class="grace-footer" v-if="cartlist.length" style="padding-left:22upx;">
			<i class="iconfont " style="padding-left:0;" :class="allEle ? 'icon_e632' :'icon_e741'"
				@tap="allElection"></i> {{$t('全选')}}
			<view style="width:40%; line-height:90upx; text-indent:1em;" v-show="editId == false">
				总计 <text style="font-size:36upx;" class="color">￥{{totalprice ? totalprice : 0.00}}</text>
			</view>
			<view style="width:40%; line-height:90upx; text-indent:1em;" v-show="editId == true">

			</view>
			<view style="width:30%;border:0;margin:6upx 0">
				<u-button type="error" shape="circle" @click="comformOrder"
					v-if="editId == false">{{$t('立即结算')}}</u-button>
				<u-button type="error" shape="circle" v-else @click="delect">{{$t('删除')}}</u-button>
			</view>
		</view>

		<!-- 领取优惠券弹窗 -->
		<popup-layer ref="popupRef" :direction="'top'">
			<view class="popup-coupon">
				<view class="popup-title">{{$t('优惠')}}</view>
				<view class="coupon-list">
					<view class="items" v-for="(getcouponlstList,getcouponlstKey) in getcouponlst"
						:key="getcouponlstKey">
						<view class="coupon-left">
							<view>{{$t('￥')}} <text>{{getcouponlstList.dec_price}}</text>{{$t('店铺优惠券')}}</view>
							<text>{{$t('满')}}{{getcouponlstList.man_price}}{{$t('使用')}}</text>
							<text>{{$t('有限期')}}{{getcouponlstList.start_time}}-{{getcouponlstList.end_time}}</text>
						</view>
						<view class="coupon-right">
							<text @click="Receive(getcouponlstList.id)"
								v-if="getcouponlstList.have == 0">{{$t('立即领取')}}</text>
							<text style="background:#999" v-if="getcouponlstList.have == 1">{{$t('已领取')}}</text>
						</view>
					</view>
				</view>

				<view class="popup-com">
					<button @click="hidePopup">{{$t('关闭')}}</button>
				</view>
			</view>
		</popup-layer>


		<popup-layer ref="comformorderRef" :direction="'top'">
			<view class="popup-coupon2">
				<view class="popup-title">{{$t('选择结算商品')}}</view>
				<view class="comformorder-title">提示：选中商品存在不同配送方式，请分开下单</view>
				<view class="comformorder-list" v-show="mailCheck.mail.length>0">
					<view class="comformorder-list-title">普通快递</view>
					<scroll-view scroll-y="true" show-scrollbar="true">
						<view class="comformorder-item">
							<view class="comformorder-image" v-for="(value, index) in mailCheck.mail" :key="index">
								<image class="comformorder-item-image" :src="value.thumb_url"></image>
							</view>
						</view>
					</scroll-view>
					<view class="comformorder-info">
						<view class="comformorder-info-left">共{{mailCheck.mail.length}}件，合计：
							<text>￥{{mailCheck.mailprice}}</text>
						</view>
						<view class="comformorder-info-right" @click="checkout(1)">结算</view>
					</view>
				</view>
				
				<view class="comformorder-list" v-show="mailCheck.home.length>0">
					<view class="comformorder-list-title">同城配送<!-- <span class="comformorder-list-subtitle">   (满38包邮)</span> --></view>
					<scroll-view scroll-y="true" show-scrollbar="false">
						<view class="comformorder-item">
							<view class="comformorder-image" v-for="(value, index) in mailCheck.home" :key="index">
								<image class="comformorder-item-image" :src="value.thumb_url"></image>
							</view>
						</view>
					</scroll-view>
					<view class="comformorder-info">
						<view class="comformorder-info-left">共{{mailCheck.home.length}}件，合计：
							<text>￥{{mailCheck.homeprice}}</text>
						</view>
						<view class="comformorder-info-right" @click="checkout(3)">结算</view>
					</view>
				</view>

				<view class="comformorder-list" v-show="mailCheck.check.length>0">
					<view class="comformorder-list-title">门店自提</view>
					<scroll-view scroll-y="true" show-scrollbar="false">
						<view class="comformorder-item">
							<view class="comformorder-image" v-for="(value, index) in mailCheck.check" :key="index">
								<image class="comformorder-item-image" :src="value.thumb_url"></image>
							</view>
						</view>
					</scroll-view>
					<view class="comformorder-info">
						<view class="comformorder-info-left">共{{mailCheck.check.length}}件，合计：
							<text>￥{{mailCheck.checkprice}}</text>
						</view>
						<view class="comformorder-info-right" @click="checkout(2)">结算</view>
					</view>
				</view>

				<view class="grace-product-attr-close comformorder-close" @click="hidePopup">
					<text class="grace-iconfont icon-close2"></text>
				</view>

			</view>
		</popup-layer>

	</view>
</template>

<script>
	import tSlideVue from "../../components/t-slide.vue"
	let shopIdList = [] // 购物车选中id
	let page = 1 // 列表分页
	let str = '编辑'
	import uniNumberBox from '../../components/uni-number-box.vue'
	
	export default {
		data() {
			return {
				//总价
				totalprice: '0.00',
				cartlist: [],
				getcouponlst: [],
				shop_id: '',
				allEle: false,
				editId: false,
				islogin: 0,
				loadingType: 0,
				isLoading: false,
				magenaText: this.$t('管理'),
				userCartNum: 0,
				imgStaticUrl: '',
				goodres: [],
				mailCheck: {
					mail: [],
					home: [],
					check: [],
					mailprice: 0,
					homeprice: 0,
					checkprice: 0,
				}
			}
		},
		onLoad() {
			this.countTotoal();
			// 线上图片地址（兼容微信小程序写法）
			this.imgStaticUrl = this.STATICURL
		},
		onShow() {
			shopIdList = []
			if (!uni.getStorageSync('token')) {
				this.islogin = 1
				return false
			}
			// page = 1
			this.islogin = 0
			this.allEle = false
			this.totalprice = '0.00';
			this.loadingType = 0
			this.userCartNum = this.$store.state.userCartNum;
			this.$store.dispatch('contentnum')

			this.getCartList()
		},

		components: {
			uniNumberBox,
			tSlideVue
		},
		watch: {
			editId(val) {
				if (val) {
					this.magenaText = this.$t('完成')
				} else {
					this.magenaText = this.$t('管理')

				}
			},
			isOpenLive(val) {

			}
		},
		methods: {
			//点击空布局按钮的回调
			emptyClick() {
				this.getnav('/pages/tabBar/category')
			},

			copyjuan(id) {
				this.shop_id = id

				this.$refs.popupRef.show()
				/**
				 * shop_id  :  商家id
				 * 获取优惠券列表
				 */
				this.$loading()
				this.$http.getcouponlst({
					shop_id: id
				}).then(res => {
					if (res.status == 200) {
						this.getcouponlst = res.data.data
					}
				})
			},

			comformOrder() {
				this.mailCheckFunction();
				let mailLength = this.mailCheck.mail.length;
				let checkLength = this.mailCheck.check.length;
				let homeLength = this.mailCheck.home.length;
	
				if ((mailLength && checkLength) || (mailLength && homeLength) || (checkLength && homeLength)) { 
					this.$refs.comformorderRef.show();
				} else if (mailLength) { 
					this.checkout(1);
				} else if (checkLength) { 
					this.checkout(2);
				} else if (homeLength) { 
					this.checkout(3);
				} else {
					return this.$toast("请选择要结算的商品");
				}
			},
			
			mailCheckFunction() {
				this.mailCheck.mail = [];//快递
				this.mailCheck.check = [];//自提
				this.mailCheck.home = [];//同城
				this.mailCheck.mailprice = 0;
				this.mailCheck.checkprice = 0;
				this.mailCheck.homeprice = 0;
				for (let p in this.cartlist) {
					for (let pp in this.cartlist[p].goodres) {
						if (!this.cartlist[p].goodres[pp].icon) {
							continue;
						}
						if (this.cartlist[p].goodres[pp].goods_type == 1) {
							let entityCheck = [...this.cartlist[p].goodres[pp].entity_check];
							if (entityCheck.includes("1")) {
								let allcheckprice = (this.cartlist[p].goodres[pp].num * this.cartlist[p].goodres[pp].shop_price).toFixed(2);
								this.mailCheck.checkprice += parseFloat(allcheckprice);
								this.mailCheck.check.push(this.cartlist[p].goodres[pp]);
							}
							if(entityCheck.includes("0")){
								let allmailprice = (this.cartlist[p].goodres[pp].num * this.cartlist[p].goodres[pp].shop_price).toFixed(2);
								this.mailCheck.mailprice += parseFloat(allmailprice);
								this.mailCheck.mail.push(this.cartlist[p].goodres[pp]);
							}
							if(entityCheck.includes("2")){
								let allhomeprice = (this.cartlist[p].goodres[pp].num * this.cartlist[p].goodres[pp].shop_price).toFixed(2);
								this.mailCheck.homeprice += parseFloat(allhomeprice);
								this.mailCheck.home.push(this.cartlist[p].goodres[pp]);
							}
						} else {
							let allcheckprice = this.cartlist[p].goodres[pp].num * this.cartlist[p].goodres[pp].shop_price;
							this.mailCheck.checkprice += allcheckprice;
							this.mailCheck.check.push(this.cartlist[p].goodres[pp]);
						}
					}
				}
				//格式化
				this.mailCheck.mailprice = (this.mailCheck.mailprice).toFixed(2);
				this.mailCheck.checkprice = (this.mailCheck.checkprice).toFixed(2);
				this.mailCheck.homeprice = (this.mailCheck.homeprice).toFixed(2);
			},



			/**
			 * coupon_id : 优惠券id
			 * 立即领取优惠券
			 */
			Receive(id) {
				this.$http.getcoupons({
					coupon_id: id,
					shop_id: this.shop_id
				}).then(res => {
					if (res.status == 200) {
						this.$toast(res.mess)
						this.getcouponlst.forEach(element => {
							if (element.id == id) {
								element.have = 1
							}
						});
					}
				})
			},
			hidePopup() {
				this.$refs.comformorderRef.close()
			},

			// 商家全选
			getShop(keys) {
				for (let k in this.cartlist) {
					if (k == keys) {
						this.cartlist[k].icon = !this.cartlist[k].icon

						if (this.cartlist[k].icon) {

							for (let l = 0; l < this.cartlist[k].goodres.length; l++) {
								this.cartlist[k].goodres[l].icon = 1
								if (!shopIdList.includes(this.cartlist[k].goodres[l].id)) {
									shopIdList.push(this.cartlist[k].goodres[l].id)
								}

							}
						} else {
							for (let l = 0; l < this.cartlist[k].goodres.length; l++) {
								this.cartlist[k].goodres[l].icon = 0
								if (shopIdList.includes(this.cartlist[k].goodres[l].id)) {
									shopIdList.forEach((el, index) => {
										if (this.cartlist[k].goodres[l].id == el) {
											shopIdList.splice(index, 1)
										}
									})

								}

							}
						}
					}
				}

				let shoplistArr = []
				for (let p in this.cartlist) {
					if (this.cartlist[p].icon) {
						shoplistArr.push(this.cartlist[p].icon)
					}
				}

				if (shoplistArr.length === Object.keys(this.cartlist).length) {
					this.allEle = 1
				} else {
					this.allEle = 0
				}

				this.countTotoal();
			},
			// 复选框
			isSelection(index, shopId) {
				let itList = []
				for (var k in this.cartlist) {
					if (this.cartlist[k].goodres[0].shop_id == shopId) {
						itList = this.cartlist[k].goodres
						for (var i = 0; i < itList.length; i++) {
							if (index == itList[i].id) {
								itList[i].icon = !itList[i].icon
								if (itList[i].icon) {
									if (!shopIdList.includes(index)) {
										shopIdList.push(index)
									}
								} else {
									if (shopIdList.includes(index)) {
										shopIdList.splice(shopIdList.indexOf(index), 1)
									}
								}
							}
						}
					}
				}
				let isSelect = []
				itList.forEach(item => {
					if (item.icon) {
						isSelect.push(item.icon)
					}
				});

				if (isSelect.length == itList.length) {
					let chArr = []
					for (let k in this.cartlist) {
						for (var a = 0; a < this.cartlist[k].goodres.length; a++) {
							if (this.cartlist[k].goodres[a].shop_id == shopId) {
								this.cartlist[k].icon = 1
							}
						}
					}
					for (let k in this.cartlist) {
						if (this.cartlist[k].icon) {
							chArr.push(chArr)
						}
					}

					if (chArr.length == this.cartlist.length) {
						this.allEle = 1
					}
				} else {
					for (let k in this.cartlist) {
						for (var a = 0; a < this.cartlist[k].goodres.length; a++) {
							if (this.cartlist[k].goodres[a].shop_id == shopId) {
								this.cartlist[k].icon = 0

							}
						}
					}

					this.allEle = 0
				}
				this.countTotoal()

			},
			allElection() {
				// 全选
				this.allEle = !this.allEle
				shopIdList = []
				if (this.allEle) {
					for (let k in this.cartlist) {
						this.cartlist[k].icon = 1
						for (var i = 0; i < this.cartlist[k].goodres.length; i++) {
							this.cartlist[k].goodres[i].icon = 1
							if (this.cartlist[k].goodres[i].icon) {
								if (!shopIdList.includes(this.cartlist[k].goodres[i].id)) {
									shopIdList.push(this.cartlist[k].goodres[i].id)
								}
							} else {
								if (shopIdList.includes(this.cartlist[k].goodres[i].id)) {
									shopIdList.splice(shopIdList.indexOf(this.cartlist[k].goodres[i].id), 1)
								}
							}
						}
					}
				} else {
					for (let k in this.cartlist) {
						this.cartlist[k].icon = 0
						for (var i = 0; i < this.cartlist[k].goodres.length; i++) {
							this.cartlist[k].goodres[i].icon = 0

						}
					}
				}
				this.countTotoal()
			},
			//计算总计函数
			countTotoal: function() {
				var total = 0;
				for (let k in this.cartlist) {
					for (var i = 0; i < this.cartlist[k].goodres.length; i++) {
						if (this.cartlist[k].goodres[i].icon == 1) {
							total += (this.cartlist[k].goodres[i].shop_price) * Number(this.cartlist[k].goodres[i]
								.num);
						}

					}
				}

				this.totalprice = total.toFixed(2);
			},
			numberChange: function(data, id) {
				for (let k in this.cartlist) {
					for (var i = 0; i < this.cartlist[k].goodres.length; i++) {
						if (this.cartlist[k].goodres[i].id == id) {
							this.cartlist[k].goodres[i].num = Number(data)
						}
					}
				}
				if (id && data) {
					this.$http.geteditcart({
						cart_id: id,
						num: data
					}).then(res => {
						if (res.status == 200) {
							//计算总价
							// this.$store.dispatch('contentnum')
							this.countTotoal();
						}
					})
				}
			},
			checkout: function(goods_type) {
				shopIdList = this.chooseShopIdList(goods_type);
				if (shopIdList.length == 0) {
					this.$toast(this.$t('请先选择商品'))
					return false
				}
				// 确认订单结算
				this.$http.getcartbuy({
					cart_idres: shopIdList.join(',')
				}).then(res => {
					//同城快递和普通物流走一个结算模式
					if (res.status == 200) {
						if(goods_type == 3){
							let gtype = goods_type == 3 ? 1 : goods_type;
							this.getnav('/pagesC/order/confirmOrder?cart_idres=' + res.data.cart_idres + '&type=' +
								2 + '&goods_type=' + gtype + '&tcType=' + goods_type + '&tcPrice=' + this.mailCheck.homeprice + '&cartFree=' + res.data.cart_free)
						}else{
							this.getnav('/pagesC/order/confirmOrder?cart_idres=' + res.data.cart_idres + '&type=' +
								2 + '&goods_type=' + goods_type)
						}
					}
				})

			},

			//选择ids
			chooseShopIdList(goods_type) {
				let shopIds = [];
				if (goods_type == 1) { 
					for (let i = 0; i < this.mailCheck.mail.length; i++) {
						shopIds.push(this.mailCheck.mail[i].id)
					}
				} else if(goods_type == 2) { 
					for (let i = 0; i < this.mailCheck.check.length; i++) {
						shopIds.push(this.mailCheck.check[i].id)
					}
				}else {
					for (let i = 0; i < this.mailCheck.home.length; i++) {
						shopIds.push(this.mailCheck.home[i].id)
					}
				}
				return shopIds;
			},

			// 删除购物车商品
			delect() {
				let isdelectList = []
				shopIdList = []
				for (let k in this.cartlist) {
					for (var i = 0; i < this.cartlist[k].goodres.length; i++) {
						if (this.cartlist[k].goodres[i].icon == 1) {
							isdelectList.push(this.cartlist[k].goodres[i].id)
						}
					}
				}
				if (isdelectList.length == 0) {
					this.$toast(this.$t('请先选择商品'))
					return false
				}
				this.$loading()
				this.$http.getdelcart({
					cart_id: isdelectList.join(',')
				}).then(res => {
					if (res.status == 200) {
						this.$toast(res.mess)
						page = 1
						this.allEle = false
						this.totalprice = 0;
						this.loadingType = 0
						this.$store.dispatch('contentnum')

						this.cartlist = []
						this.getCartList()
						this.$nextTick(() => {
							this.editId = false

						})
					}
				})
			},
			del(data) {
				this.$http.getdelcart({
					cart_id: data.id
				}).then(res => {
					if (res.status == 200) {
						this.$toast(res.mess)
						page = 1
						this.cartlist = []
						this.totalprice = '0.00';
						this.allEle = false
						this.loadingType = 0
						this.$store.dispatch('contentnum')
						this.getCartList()
						this.$nextTick(() => {
							this.editId = false

						})
					}
				})
			},
			goPage(val) {
				uni.navigateTo({
					url: '/pagesC/goods/goodsDetails?id=' + val.goods_id
				})
			},
			// 获取购物车信息
			getCartList(isFrash) {
				if (this.isLoading) return
				this.isLoading = true
				this.$http.getCartList({
					page: page
				}).then(res => {
					if (res.status == 200) {
						this.userCartNum = this.$store.state.userCartNum;
						this.isLoading = false
						if (page == 1) {
							this.cartlist = res.data
							this.cartlist[0].goodres.forEach(val => {
								this.$set(val, 'isTouchMove', false)
							})
							this.goodres = this.cartlist[0].goodres
							return false
						}

						if (res.data.length == 0) {
							this.loadingType = 2
							return false
						}

						if (isFrash) {
							this.cartlist = res.data
						} else {
							this.cartlist = [...this.cartlist, ...res.data]
						}

						this.loadingType = 0
					}
				}).catch(err => {
					this.isLoading = false
				})
			},
			manage() {
				this.editId = !this.editId
			}
		},
		onPullDownRefresh() {
			page = 1
			this.loadingType = 0
			this.$nextTick(() => {
				this.getCartList(true)
			})
		},
		onReachBottom() {
			if (this.loadingType == 1 || this.loadingType == 2) {
				return false
			}
			this.loadingType = 1

			page++
			this.getCartList()
		},

	}
</script>

<style lang="scss" scoped>
	.comformorder-list {
		margin: 0 10upx;

		.comformorder-list-title {
			font-size: 30upx;
			font-weight: bold;
			height: 80upx;
			line-height: 80upx;
		}

		.comformorder-item {
			display: flex;
			flex-direction: row;

			.comformorder-image {
				margin-right: 10upx;

				.comformorder-item-image {
					width: 200upx;
					height: 200upx;
				}
			}
		}

		.comformorder-info {
			height: 90upx;
			line-height: 90upx;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			margin: 0 10upx;

			.comformorder-info-left {
				font-size: 30upx;

				text {
					color: #f00;
				}
			}

			.comformorder-info-right {
				background: #f00;
				height: 70upx;
				line-height: 70upx;
				width: 150upx;
				text-align: center;
				color: #FFFFFF;
				margin-top: 20upx;
				border-radius: 30upx;
			}
		}
	}

	.comformorder-title {
		color: #878787;
		margin: 0 10upx;
	}

	.comformorder-close {
		position: fixed;
		right: 10upx;
		top: 0;
	}

	.cartWrap {
		.cartCard {
			background-color: #fff;
			margin: 25upx;
			border-radius: 16upx;

			.goodsCover {
				flex-shrink: 0;
				margin-right: 10upx;
				border-radius: 20upx;
			}
		}
	}

	.grace-footer {
		display: flex;
		justify-content: space-between;
		/*  #ifdef  H5 */
		margin-bottom: 100upx;
		/*  #endif  */
		/*  #ifdef  APP-PLUS*/
		margin-bottom: 0upx;

		/*  #endif  */
		box-shadow: none;
	}

	.mescroll-empty .empty-icon {
		width: 75% !important;
	}

	.tipInfo {
		font-size: 30upx;
		font-weight: 400;
	}

	.panel1 {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10upx 30upx;
	}

	.grace_discount {
		padding: 15upx;
		color: #999;
		font-size: 20upx;
	}
</style>